package org.quincy.rock.core.dao.sql;

import org.apache.commons.lang3.StringUtils;
import org.quincy.rock.core.dao.NameInterceptor;
import org.quincy.rock.core.dao.ValueInterceptor;
import org.quincy.rock.core.util.StringUtil;

/**
 * <b>JoinOn。</b>
 * <p><b>详细说明：</b></p>
 * <!-- 在此添加详细说明 -->
 * 无。
 * 
 * @version 1.0
 * @author wks
 * @since 1.0
 */
public class JoinOn extends AbstractExpression {
	/**
	 * serialVersionUID。
	 */
	private static final long serialVersionUID = 1336095165931893471L;

	/**
	 * 表连接类型。
	 */
	private JoinType joinType;

	/**
	 * 表名。
	 */
	private String tableName;

	/**
	 * 表别名。
	 */
	private String tableAlias;

	/**
	 * on连接条件。
	 */
	private Predicate on;

	/**
	 * on连接条件表达式。
	 */
	private String onExpr;

	public JoinOn() {
		super();
	}

	protected JoinOn(JoinType joinType, String tableName, String tableAlias, String onExpr) {
		this.joinType = joinType;
		this.tableName = tableName;
		this.tableAlias = tableAlias;
		this.onExpr = onExpr;
	}

	public JoinType joinType() {
		return joinType == null ? JoinType.LEFT_JOIN : joinType;
	}

	@SuppressWarnings("unchecked")
	public <T extends JoinOn> T joinType(JoinType joinType) {
		this.joinType = joinType;
		return (T) this;
	}

	public String getJoinType() {
		return joinType().op();
	}

	public void setJoinType(String joinType) {
		this.joinType = JoinType.of(joinType);
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public String getTableAlias() {
		return tableAlias;
	}

	public void setTableAlias(String tableAlias) {
		this.tableAlias = tableAlias;
	}

	public Predicate getOn() {
		if (on == null)
			on = new Predicate();
		return on;
	}

	public void setOn(Predicate on) {
		this.on = on;
	}

	public String getOnExpr() {
		return onExpr;
	}

	public void setOnExpr(String onExpr) {
		this.onExpr = onExpr;
	}

	public boolean hasAlias() {
		return StringUtils.isNotBlank(tableAlias);
	}

	public boolean useOnExpr() {
		return StringUtils.isNotBlank(onExpr);
	}

	@Override
	public StringBuilder build(StringBuilder buffer, NameInterceptor nameInterceptor,
			ValueInterceptor valueInterceptor) {
		buffer.append(joinType().op()).append(StringUtil.CHAR_SPACE)
				.append(nameInterceptor == null ? tableName : nameInterceptor.applyTableName(tableName))
				.append(StringUtil.CHAR_SPACE);
		if (hasAlias())
			buffer.append(getTableAlias()).append(StringUtil.CHAR_SPACE);
		buffer.append("on").append(StringUtil.CHAR_SPACE);
		if (useOnExpr())
			buffer.append(getOnExpr());
		else
			getOn().build(buffer, nameInterceptor, valueInterceptor);
		return buffer;
	}
}
